document.addEventListener('DOMContentLoaded', () => {
    // 加载用户设置函数
    function loadUserSettings() {
        // 加载级别筛选器设置
        const savedLevelFilter = UserSettings.get('levelFilter');
        if (savedLevelFilter && levelFilter) {
            try {
                // 尝试解析JSON字符串
                const selectedLevels = JSON.parse(savedLevelFilter);
                if (Array.isArray(selectedLevels)) {
                    // 获取所有级别复选框
                    const levelCheckboxes = levelFilter.querySelectorAll('input[type="checkbox"]');
                    
                    // 先取消所有选择
                    levelCheckboxes.forEach(checkbox => {
                        checkbox.checked = false;
                    });
                    
                    // 设置保存的选择
                    selectedLevels.forEach(level => {
                        const checkbox = levelFilter.querySelector(`input[value="${level}"]`);
                        if (checkbox) checkbox.checked = true;
                    });
                    
                    // 更新按钮文本
                    updateLevelFilterText();
                }
            } catch (e) {
                // 如果解析失败，默认选中"所有级别"
                const allLevelCheckbox = document.getElementById('level-all');
                if (allLevelCheckbox) allLevelCheckbox.checked = true;
                updateLevelFilterText();
            }
        } else {
            // 如果没有保存的设置，默认选中"所有级别"
            const allLevelCheckbox = document.getElementById('level-all');
            if (allLevelCheckbox) allLevelCheckbox.checked = true;
            updateLevelFilterText();
        }
    }
    
    // 全局变量声明
    let socket = null;
    let logs = [];
    let modules = new Set();
    let devices = new Map();
    let activeDevices = new Set();
    let deviceSessions = new Map();
    let sessionLogs = new Map();
    let sessionCollapseStates = new Map();
    let selectedDevice = null;
    let autoScroll = true;
    let useDeduplication = true;
    let viewMode = 'table';
    let reconnectAttempts = 0;
    let reconnectTimeout = null;
    const maxReconnectAttempts = 5;
    const reconnectInterval = 3333;
    let contextMenuVisible = false;

    // DOM元素
    const logContainer = document.getElementById('log-container');
    const levelFilter = document.getElementById('level-filter');
    const moduleFilter = document.getElementById('module-filter');
    const sessionFilter = document.getElementById('session-filter');
    const searchInput = document.getElementById('search-input');
    const clearLogsBtn = document.getElementById('clear-logs');
    const toggleAutoScrollBtn = document.getElementById('toggle-auto-scroll');
    const toggleDeduplicationBtn = document.getElementById('toggle-deduplication');
    const statusIndicator = document.getElementById('status-indicator');
    const statusText = document.getElementById('status-text');
    const logCount = document.getElementById('log-count');
    const currentSessionId = document.getElementById('current-session-id');
    const activeDevicesCount = document.getElementById('active-devices-count');
    const sidebarToggle = document.getElementById('sidebar-toggle');
    const sidebar = document.querySelector('.sidebar');
    const deviceTotalSessions = document.getElementById('device-total-sessions');
    const deviceFirstConnected = document.getElementById('device-first-connected');
    const copySessionBtn = document.getElementById('copy-session-id');
    const toast = document.getElementById('toast');
    const backToRealtimeBtn = document.getElementById('back-to-realtime');
    const collapseAllSessionsBtn = document.getElementById('collapse-all-sessions');

    // 缓存管理
    const CacheManager = {
        KEYS: {
            USER_SETTINGS: 'log_monitor_user_settings',
            DEVICE_STATES: 'log_monitor_device_states',
            LOG_CACHE: 'log_monitor_log_cache',
            SESSION_STATES: 'log_monitor_session_states',
            LAST_UPDATE: 'log_monitor_last_update'
        },
        
        get(key, defaultValue = null) {
            try {
                const data = localStorage.getItem(key);
                return data ? JSON.parse(data) : defaultValue;
            } catch (error) {
                console.warn('获取缓存失败:', error);
                return defaultValue;
            }
        },
        
        set(key, value) {
            try {
                localStorage.setItem(key, JSON.stringify(value));
                return true;
            } catch (error) {
                console.warn('设置缓存失败:', error);
                return false;
            }
        },
        
        remove(key) {
            try {
                localStorage.removeItem(key);
                return true;
            } catch (error) {
                console.warn('删除缓存失败:', error);
                return false;
            }
        },
        
        clear() {
            try {
                Object.values(this.KEYS).forEach(key => {
                    localStorage.removeItem(key);
                });
                return true;
            } catch (error) {
                console.warn('清除缓存失败:', error);
                return false;
            }
        },
        
        getSize() {
            try {
                let size = 0;
                Object.values(this.KEYS).forEach(key => {
                    const data = localStorage.getItem(key);
                    if (data) {
                        size += data.length;
                    }
                });
                return size;
            } catch (error) {
                console.warn('获取缓存大小失败:', error);
                return 0;
            }
        }
    };
    
    // 用户设置管理
    const UserSettings = {
        defaults: {
            autoScroll: true,
            useDeduplication: true,
            selectedDevice: null,
            levelFilter: 'all',
            moduleFilter: 'all',
            sessionFilter: 'all',
            searchText: '',
            filtersExpanded: window.innerWidth >= 768,
            sidebarCollapsed: false,
            viewMode: 'table'
        },
        
        load() {
            const saved = CacheManager.get(CacheManager.KEYS.USER_SETTINGS, {});
            return { ...this.defaults, ...saved };
        },
        
        save(settings) {
            const current = this.load();
            const updated = { ...current, ...settings };
            return CacheManager.set(CacheManager.KEYS.USER_SETTINGS, updated);
        },
        
        get(key) {
            const settings = this.load();
            return settings[key];
        },
        
        set(key, value) {
            const settings = this.load();
            settings[key] = value;
            return this.save(settings);
        },
        
        reset() {
            return CacheManager.set(CacheManager.KEYS.USER_SETTINGS, this.defaults);
        }
    };
    
    // 日志数据缓存管理
    const LogCache = {
        MAX_CACHE_SIZE: 1000,
        CACHE_EXPIRE_TIME: 30 * 60 * 1000, // 30分钟
        
        load() {
            const cached = CacheManager.get(CacheManager.KEYS.LOG_CACHE, {
                logs: [],
                timestamp: 0,
                modules: []
            });
            
            if (Date.now() - cached.timestamp > this.CACHE_EXPIRE_TIME) {
                console.log('日志缓存已过期，清空缓存');
                return { logs: [], modules: [] };
            }
            
            return {
                logs: cached.logs || [],
                modules: cached.modules || []
            };
        },
        
        save(logs, modules) {
            const logsToCache = logs.length > this.MAX_CACHE_SIZE 
                ? logs.slice(-this.MAX_CACHE_SIZE) 
                : logs;
            
            const cacheData = {
                logs: logsToCache,
                modules: Array.from(modules),
                timestamp: Date.now()
            };
            
            return CacheManager.set(CacheManager.KEYS.LOG_CACHE, cacheData);
        },
        
        clear() {
            return CacheManager.remove(CacheManager.KEYS.LOG_CACHE);
        },
        
        addLog(log) {
            const cached = this.load();
            cached.logs.push(log);
            
            if (log.module && !cached.modules.includes(log.module)) {
                cached.modules.push(log.module);
            }
            
            this.save(cached.logs, new Set(cached.modules));
        }
    };
    
    // 设备状态缓存管理
    const DeviceCache = {
        CACHE_EXPIRE_TIME: 5 * 60 * 1000, // 5分钟
        
        load() {
            const cached = CacheManager.get(CacheManager.KEYS.DEVICE_STATES, {
                devices: {},
                activeDevices: [],
                deviceSessions: {},
                timestamp: 0
            });
            
            if (Date.now() - cached.timestamp > this.CACHE_EXPIRE_TIME) {
                console.log('设备状态缓存已过期，清空缓存');
                return {
                    devices: {},
                    activeDevices: [],
                    deviceSessions: {}
                };
            }
            
            return {
                devices: cached.devices || {},
                activeDevices: cached.activeDevices || [],
                deviceSessions: cached.deviceSessions || {}
            };
        },
        
        save(devices, activeDevices, deviceSessions) {
            const cacheData = {
                devices: Object.fromEntries(devices),
                activeDevices: Array.from(activeDevices),
                deviceSessions: Object.fromEntries(deviceSessions),
                timestamp: Date.now()
            };
            
            return CacheManager.set(CacheManager.KEYS.DEVICE_STATES, cacheData);
        },
        
        clear() {
            return CacheManager.remove(CacheManager.KEYS.DEVICE_STATES);
        }
    };

    // 会话状态缓存管理
    const SessionCache = {
        save() {
            const sessionData = {
                sessionLogs: Object.fromEntries(sessionLogs),
                sessionCollapseStates: Object.fromEntries(sessionCollapseStates),
                timestamp: Date.now()
            };
            return CacheManager.set(CacheManager.KEYS.SESSION_STATES, sessionData);
        },
        
        load() {
            const cached = CacheManager.get(CacheManager.KEYS.SESSION_STATES, {
                sessionLogs: {},
                sessionCollapseStates: {},
                timestamp: 0
            });
            
            return {
                sessionLogs: cached.sessionLogs || {},
                sessionCollapseStates: cached.sessionCollapseStates || {}
            };
        },
        
        clear() {
            return CacheManager.remove(CacheManager.KEYS.SESSION_STATES);
        }
    };

    // 工具函数
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    function formatTimestamp(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }

    // 从缓存恢复应用状态
    function restoreFromCache() {
        console.log('开始从缓存恢复应用状态...');
        
        // 恢复用户设置
        const settings = UserSettings.load();
        applyUserSettings(settings);
        
        // 恢复设备状态
        const deviceCache = DeviceCache.load();
        if (Object.keys(deviceCache.devices).length > 0) {
            console.log('从缓存恢复设备状态');
            devices = new Map(Object.entries(deviceCache.devices));
            activeDevices = new Set(deviceCache.activeDevices);
            deviceSessions = new Map(Object.entries(deviceCache.deviceSessions));
            
            updateDeviceList();
            updateActiveDevicesCount();
            
            // 恢复选中的设备
            if (settings.selectedDevice && devices.has(settings.selectedDevice)) {
                selectedDevice = settings.selectedDevice;
                switchDevice(selectedDevice, false); // false表示不重新加载数据
            }
        }
        
        // 恢复日志数据
        const logCache = LogCache.load();
        if (logCache.logs.length > 0) {
            console.log(`从缓存恢复 ${logCache.logs.length} 条日志`);
            logs = logCache.logs;
            modules = new Set(logCache.modules);
            
            updateModuleFilter();
            renderLogs();
            updateLogCount();
        }
        
        // 恢复会话状态
        const sessionCache = SessionCache.load();
        if (Object.keys(sessionCache.sessionLogs).length > 0) {
            console.log('从缓存恢复会话状态');
            sessionLogs = new Map(Object.entries(sessionCache.sessionLogs));
            sessionCollapseStates = new Map(Object.entries(sessionCache.sessionCollapseStates));
        }
        
        console.log('缓存恢复完成');
    }
    
    // 应用用户设置
    function applyUserSettings(settings = null) {
        if (!settings) {
            settings = UserSettings.load();
        }
        
        // 应用自动滚动设置
        autoScroll = settings.autoScroll;
        if (toggleAutoScrollBtn) {
            toggleAutoScrollBtn.classList.toggle('active', autoScroll);
            toggleAutoScrollBtn.title = autoScroll ? '关闭自动滚动' : '开启自动滚动';
        }
        
        // 应用去重设置
        useDeduplication = settings.useDeduplication;
        if (toggleDeduplicationBtn) {
            toggleDeduplicationBtn.classList.toggle('active', useDeduplication);
            toggleDeduplicationBtn.title = useDeduplication ? '关闭去重模式' : '开启去重模式';
        }
        
        // 应用过滤器设置
        if (levelFilter) levelFilter.value = settings.levelFilter;
        if (moduleFilter) {
            // 处理可能存在的旧版本JSON格式的moduleFilter设置
            if (settings.moduleFilter && settings.moduleFilter.startsWith('[')) {
                try {
                    const modules = JSON.parse(settings.moduleFilter);
                    moduleFilter.value = modules.length > 0 ? modules[0] : 'all';
                } catch (e) {
                    moduleFilter.value = 'all';
                }
            } else {
                moduleFilter.value = settings.moduleFilter || 'all';
            }
        }
        if (sessionFilter) sessionFilter.value = settings.sessionFilter;
        if (searchInput) searchInput.value = settings.searchText;
        
        // 应用过滤器展开状态
        const filterSecondary = document.getElementById('filter-secondary');
        const filtersToggle = document.getElementById('filters-toggle');
        if (filterSecondary && filtersToggle) {
            if (settings.filtersExpanded) {
                filterSecondary.classList.add('expanded');
                filtersToggle.classList.add('expanded');
                filtersToggle.title = '收起过滤器';
            } else {
                filterSecondary.classList.remove('expanded');
                filtersToggle.classList.remove('expanded');
                filtersToggle.title = '展开更多过滤器';
            }
        }
        
        // 应用侧边栏状态（仅在桌面端）
        if (window.innerWidth > 1024 && sidebar) {
            if (settings.sidebarCollapsed) {
                sidebar.classList.add('collapsed');
            } else {
                sidebar.classList.remove('collapsed');
            }
        }
        
        // 应用视图模式
        viewMode = settings.viewMode;
        
        console.log('已应用用户设置:', settings);
    }
    
    // 保存当前设置
    function saveCurrentSettings() {
        const settings = {
            autoScroll: autoScroll,
            useDeduplication: useDeduplication,
            selectedDevice: selectedDevice,
            levelFilter: levelFilter ? levelFilter.value : 'all',
            moduleFilter: moduleFilter ? moduleFilter.value : 'all',
            sessionFilter: sessionFilter ? sessionFilter.value : 'all',
            searchText: searchInput ? searchInput.value : '',
            filtersExpanded: document.getElementById('filter-secondary')?.classList.contains('expanded') || false,
            sidebarCollapsed: sidebar?.classList.contains('collapsed') || false,
            viewMode: viewMode
        };
        
        UserSettings.save(settings);
        
        // 同时保存其他状态到缓存
        LogCache.save(logs, modules);
        DeviceCache.save(devices, activeDevices, deviceSessions);
        SessionCache.save();
    }

    // 定期保存状态到缓存
    function startAutoSave() {
        setInterval(() => {
            saveCurrentSettings();
        }, 10000); // 每10秒保存一次
    }

    // 页面卸载时保存状态
    window.addEventListener('beforeunload', () => {
        saveCurrentSettings();
    });

    // 页面可见性变化时保存状态
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            saveCurrentSettings();
        }
    });    
    // 初始化过滤器事件监听
    function initFilterEvents() {
        // 级别过滤器 - 弹窗模式
        const levelFilterBtn = document.getElementById('level-filter-btn');
        const levelFilterModal = document.getElementById('level-filter-modal');
        const levelFilterText = document.getElementById('level-filter-text');
        const applyLevelFilterBtn = document.getElementById('apply-level-filter');
        const resetLevelFilterBtn = document.getElementById('reset-level-filter');
        const closeLevelFilterBtn = document.getElementById('close-level-modal');
        
        if (levelFilterBtn && levelFilterModal) {
            // 打开弹窗
            levelFilterBtn.addEventListener('click', () => {
                levelFilterModal.classList.add('active');
                levelFilterBtn.classList.add('active');
            });
            
            // 关闭弹窗
            const closeLevelFilter = () => {
                levelFilterModal.classList.remove('active');
                levelFilterBtn.classList.remove('active');
            };
            
            // 点击关闭按钮
            if (closeLevelFilterBtn) {
                closeLevelFilterBtn.addEventListener('click', closeLevelFilter);
            }
            
            // 点击遮罩层关闭
            levelFilterModal.addEventListener('click', (e) => {
                if (e.target === levelFilterModal) {
                    closeLevelFilter();
                }
            });
            
            // ESC键关闭
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && levelFilterModal.classList.contains('active')) {
                    closeLevelFilter();
                }
            });
        }
        
        // 级别过滤器复选框逻辑
        if (levelFilter) {
            // 获取所有级别复选框
            const levelCheckboxes = levelFilter.querySelectorAll('input[type="checkbox"]');
            const allLevelCheckbox = document.getElementById('level-all');
            
            // 为每个复选框添加事件监听
            levelCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', () => {
                    // 处理"所有级别"选项的特殊逻辑
                    if (checkbox.value === 'all') {
                        // 如果选择了"所有级别"，取消其他所有选项
                        levelCheckboxes.forEach(cb => {
                            if (cb.value !== 'all') {
                                cb.checked = false;
                            }
                        });
                    } else {
                        // 如果选择了其他选项，取消"所有级别"选项
                        allLevelCheckbox.checked = false;
                        
                        // 如果没有任何选项被选中，自动选中"所有级别"
                        const anyChecked = Array.from(levelCheckboxes).some(cb => cb.value !== 'all' && cb.checked);
                        if (!anyChecked) {
                            allLevelCheckbox.checked = true;
                        }
                    }
                    
                    // 更新按钮文本
                    updateLevelFilterText();
                });
            });
            
            // 应用按钮
            if (applyLevelFilterBtn) {
                applyLevelFilterBtn.addEventListener('click', () => {
                    applyFilters();
                    
                    // 保存选中的值
                    const selectedLevels = Array.from(levelCheckboxes)
                        .filter(cb => cb.checked)
                        .map(cb => cb.value);
                    UserSettings.set('levelFilter', JSON.stringify(selectedLevels));
                    
                    // 关闭弹窗
                    levelFilterModal.classList.remove('active');
                    levelFilterBtn.classList.remove('active');
                });
            }
            
            // 重置按钮
            if (resetLevelFilterBtn) {
                resetLevelFilterBtn.addEventListener('click', () => {
                    // 重置为"所有级别"
                    levelCheckboxes.forEach(cb => {
                        cb.checked = cb.value === 'all';
                    });
                    updateLevelFilterText();
                });
            }
        }
        
        // 更新级别筛选按钮文本
        window.updateLevelFilterText = function() {
            const levelFilterText = document.getElementById('level-filter-text');
            if (!levelFilterText || !levelFilter) return;
            
            const levelCheckboxes = levelFilter.querySelectorAll('input[type="checkbox"]');
            const selectedLevels = Array.from(levelCheckboxes)
                .filter(cb => cb.checked && cb.value !== 'all')
                .map(cb => cb.nextElementSibling.textContent);
            
            if (selectedLevels.length === 0 || document.getElementById('level-all').checked) {
                levelFilterText.textContent = '所有级别';
            } else if (selectedLevels.length === 1) {
                levelFilterText.textContent = selectedLevels[0];
            } else {
                levelFilterText.textContent = `${selectedLevels.length}个级别`;
            }
        };
        
        // 模块过滤器
        if (moduleFilter) {
        moduleFilter.addEventListener('change', () => {
            applyFilters();
            // 保存选中的值
            UserSettings.set('moduleFilter', moduleFilter.value);
        });
        }
        
        // 会话过滤器
        if (sessionFilter) {
            sessionFilter.addEventListener('change', () => {
                const selectedValue = sessionFilter.value;
                
                // 如果选择了特定会话（不是'all'或'current'），切换到历史模式
                if (selectedValue !== 'all' && selectedValue !== 'current') {
                    updateStatusIndicator('history', '', selectedValue);
                } else {
                    // 如果选择了'all'或'current'，切换到实时模式
                    updateStatusIndicator('realtime');
                }
                
                applyFilters();
                UserSettings.set('sessionFilter', sessionFilter.value);
            });
        }
        
        // 搜索输入
        if (searchInput) {
            searchInput.addEventListener('input', debounce(() => {
                applyFilters();
                UserSettings.set('searchText', searchInput.value);
            }, 300));
        }
        
        // 自动滚动切换
        if (toggleAutoScrollBtn) {
            toggleAutoScrollBtn.addEventListener('click', () => {
                autoScroll = !autoScroll;
                toggleAutoScrollBtn.classList.toggle('active', autoScroll);
                toggleAutoScrollBtn.title = autoScroll ? '关闭自动滚动' : '开启自动滚动';
                UserSettings.set('autoScroll', autoScroll);
            });
        }
        
        // 去重模式切换
        if (toggleDeduplicationBtn) {
            toggleDeduplicationBtn.addEventListener('click', () => {
                useDeduplication = !useDeduplication;
                toggleDeduplicationBtn.classList.toggle('active', useDeduplication);
                toggleDeduplicationBtn.title = useDeduplication ? '关闭去重模式' : '开启去重模式';
                UserSettings.set('useDeduplication', useDeduplication);
                applyFilters();
            });
        }
        
        // 清除日志
        if (clearLogsBtn) {
            clearLogsBtn.addEventListener('click', () => {
                if (confirm('确定要清除所有日志吗？')) {
                    logs = [];
                    modules.clear();
                    sessionLogs.clear();
                    sessionCollapseStates.clear();
                    logContainer.innerHTML = '';
                    updateLogCount();
                    updateModuleFilter();
                    
                    // 清除日志缓存
                    LogCache.clear();
                    SessionCache.clear();
                    console.log('已清除日志和缓存');
                }
            });
        }
    }

    // 初始化WebSocket连接
    function initWebSocket() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const host = window.location.hostname || 'localhost';
        const port = 3333;
        const wsUrl = `${protocol}//${host}:${port}`;
        
        statusIndicator.classList.remove('connected');
        statusIndicator.classList.add('connecting');
        statusText.textContent = '正在连接...';

        socket = new WebSocket(wsUrl);

        socket.onopen = () => {
            console.log('WebSocket连接已建立');
            statusIndicator.classList.remove('connecting');
            statusIndicator.classList.add('connected');
            statusText.textContent = '已连接';
            reconnectAttempts = 0;
            if (reconnectTimeout) {
                clearTimeout(reconnectTimeout);
                reconnectTimeout = null;
            }
            
            // 连接成功后，重新加载最新数据
            loadDevices();
            loadActiveDevices();
        };

        socket.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.type === 'log') {
                    const logData = data.data;
                    addLog(logData);
                    
                    if (logData.sessionId) {
                        const count = sessionLogs.get(logData.sessionId) || 0;
                        sessionLogs.set(logData.sessionId, count + 1);
                    }
                    
                    if (logData.deviceId) {
                        markDeviceHasNewLogs(logData.deviceId);
                    }
                    
                } else if (data.type === 'device_registered') {
                    console.log('设备注册成功:', data);
                    loadDevices();
                    loadActiveDevices();
                } else {
                    addLog(data);
                }
            } catch (error) {
                console.error('解析消息失败:', error);
            }
        };

        socket.onclose = () => {
            console.log('WebSocket连接已关闭');
            statusIndicator.classList.remove('connected', 'connecting');
            statusText.textContent = '连接已断开';
            
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                statusText.textContent = `连接已断开，${reconnectInterval/1000}秒后重试 (${reconnectAttempts}/${maxReconnectAttempts})`;
                reconnectTimeout = setTimeout(initWebSocket, reconnectInterval);
            } else {
                statusText.textContent = '连接失败，请刷新页面重试';
            }
        };

        socket.onerror = (error) => {
            console.error('WebSocket错误:', error);
        };
    }

    // 设备管理函数
    function loadDevices() {
        fetch('/api/devices')
            .then(response => response.json())
            .then(data => {
                devices.clear();
                data.forEach(device => {
                    devices.set(device.id, device);
                });
                updateDeviceList();
                
                DeviceCache.save(devices, activeDevices, deviceSessions);
                
                // 如果没有选中设备且有缓存的选择，恢复选择
                const savedDevice = UserSettings.get('selectedDevice');
                if (!selectedDevice && savedDevice && devices.has(savedDevice)) {
                    switchDevice(savedDevice);
                } else if (devices.size > 0 && !selectedDevice) {
                    const firstActiveDevice = Array.from(devices.keys()).find(deviceId => activeDevices.has(deviceId));
                    if (firstActiveDevice) {
                        switchDevice(firstActiveDevice);
                    } else {
                        const firstDevice = Array.from(devices.keys())[0];
                        if (firstDevice) {
                            switchDevice(firstDevice);
                        }
                    }
                }
            })
            .catch(error => console.error('加载设备列表失败:', error));
    }

    function loadActiveDevices() {
        fetch('/api/active-devices')
            .then(response => response.json())
            .then(data => {
                activeDevices.clear();
                data.forEach(deviceId => {
                    activeDevices.add(deviceId);
                });
                updateActiveDevicesCount();
                updateDeviceList();
                
                DeviceCache.save(devices, activeDevices, deviceSessions);
            })
            .catch(error => console.error('加载活跃设备失败:', error));
    }

    function updateActiveDevicesCount() {
        if (activeDevicesCount) {
            activeDevicesCount.textContent = activeDevices.size;
        }
    }

    function updateDeviceList() {
        const deviceList = document.getElementById('device-list');
        if (!deviceList) return;

        deviceList.innerHTML = '';

        devices.forEach((device, deviceId) => {
            const deviceItem = document.createElement('div');
            deviceItem.className = 'device-item';
            deviceItem.setAttribute('data-device', deviceId);
            
            const isActive = activeDevices.has(deviceId);
            if (isActive) {
                deviceItem.classList.add('active');
            }
            
            if (deviceId === selectedDevice) {
                deviceItem.classList.add('selected');
            }
            
            // 添加设备信息，使用图标颜色表示在线/离线状态
            deviceItem.innerHTML = `
                <div class="device-info">
                    <span class="material-icons device-icon ${isActive ? 'online' : 'offline'}">computer</span>
                    <span class="device-name">${device.name || deviceId}</span>
                </div>
            `;
            
            // 点击设备切换到该设备
            deviceItem.querySelector('.device-info').addEventListener('click', () => switchDevice(deviceId));
            
            // 添加右键菜单事件
            deviceItem.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                showContextMenu(e, deviceId);
            });
            
            deviceList.appendChild(deviceItem);
        });
    }

    function clearLogDisplay() {
        // 清空日志显示
        if (logContainer) {
            logContainer.innerHTML = '';
        }
        
        // 重置相关数据
        logs = [];
        modules.clear();
        sessionLogs.clear();
        sessionCollapseStates.clear();
        
        // 更新计数
        updateLogCount();
        
        // 更新模块过滤器
        updateModuleFilter();
    }

    function deleteDevice(deviceId) {
        if (!deviceId) return;
        
        // 确认删除
        if (!confirm(`确定要删除设备 ${deviceId} 吗？这将删除该设备的所有日志和会话数据。`)) {
            return;
        }
        
        // 调用删除设备API
        fetch(`/api/devices/${deviceId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 从设备列表中移除
                devices.delete(deviceId);
                
                // 如果删除的是当前选中的设备，则切换到其他设备
                if (deviceId === selectedDevice) {
                    selectedDevice = null;
                    // 尝试选择第一个活跃设备
                    const firstActiveDevice = Array.from(devices.keys()).find(id => activeDevices.has(id));
                    if (firstActiveDevice) {
                        switchDevice(firstActiveDevice);
                    } else if (devices.size > 0) {
                        // 如果没有活跃设备，选择第一个设备
                        switchDevice(Array.from(devices.keys())[0]);
                    } else {
                        // 如果没有设备了，清空日志显示
                        clearLogDisplay();
                    }
                }
                
                // 更新设备列表
                updateDeviceList();
                
                // 显示成功消息
                showToast(`设备 ${deviceId} 已成功删除`);
            } else {
                // 显示错误消息
                showToast(`删除设备失败: ${data.error || '未知错误'}`, 'error');
            }
        })
        .catch(error => {
            console.error('删除设备失败:', error);
            showToast('删除设备失败，请查看控制台获取详细信息', 'error');
        });
    }
    
    function switchDevice(deviceId, loadData = true) {
        selectedDevice = deviceId;
        UserSettings.set('selectedDevice', deviceId);
        
        document.querySelectorAll('.device-item').forEach(item => {
            item.classList.remove('selected');
        });
        
        const selectedItem = document.querySelector(`[data-device="${deviceId}"]`);
        if (selectedItem) {
            selectedItem.classList.add('selected');
        }
        
        if (sessionFilter) {
            sessionFilter.value = 'all';
            UserSettings.set('sessionFilter', 'all');
        }
        
        // 更新状态指示器为实时模式
        updateStatusIndicator('realtime');
        
        if (loadData) {
            loadDeviceStats(deviceId);
            loadDeviceSessions(deviceId);
        }
        
        applyFilters();
    }

    function loadDeviceStats(deviceId) {
        if (!deviceId) return;
        
        fetch(`/api/device-stats/${deviceId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(response => {
                const data = response.data;
                if (deviceTotalSessions) {
                    deviceTotalSessions.textContent = data.total_sessions || 0;
                }
                if (deviceFirstConnected) {
                    deviceFirstConnected.textContent = data.first_connected ? 
                        new Date(data.first_connected).toLocaleString() : '-';
                }
                
                if (currentSessionId && data.current_session_id) {
                    currentSessionId.textContent = data.current_session_id;
                } else if (currentSessionId) {
                    currentSessionId.textContent = '-';
                }
            })
            .catch(error => console.error('加载设备统计失败:', error));
    }

    function loadDeviceSessions(deviceId) {
        if (!deviceId) return;
        
        fetch(`/api/devices/${deviceId}/sessions`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                deviceSessions.set(deviceId, data);
                updateSessionInfo(deviceId);
                updateSessionFilter(data);
                
                DeviceCache.save(devices, activeDevices, deviceSessions);
            })
            .catch(error => console.error('加载设备会话失败:', error));
    }

    function updateSessionInfo(deviceId) {
        const sessions = deviceSessions.get(deviceId) || [];
        const activeSession = sessions.find(s => s.is_active);
        
        if (currentSessionId) {
            if (activeSession) {
                currentSessionId.textContent = activeSession.id;
            } else {
                currentSessionId.textContent = '-';
            }
        }
    }

    function updateSessionFilter(sessions) {
        if (!sessionFilter) return;
        
        // 保存当前选择
        const currentValue = sessionFilter.value;
        
        // 清空选项（保留默认选项）
        sessionFilter.innerHTML = `
            <option value="all">所有会话</option>
            <option value="current">当前会话</option>
        `;
        
        // 添加会话选项
        sessions.forEach(session => {
            const option = document.createElement('option');
            option.value = session.id;
            option.textContent = `会话 ${session.id.substring(0, 8)}...`;
            sessionFilter.appendChild(option);
        });
        
        // 恢复选择
        if (currentValue && Array.from(sessionFilter.options).some(opt => opt.value === currentValue)) {
            sessionFilter.value = currentValue;
        }
    }

    function markDeviceHasNewLogs(deviceId) {
        const deviceItem = document.querySelector(`[data-device="${deviceId}"]`);
        if (deviceItem) {
            deviceItem.classList.add('has-new-logs');
        }
    }

    // 日志处理函数
    function addLog(logData) {
        logs.push(logData);
        
        if (logData.module) {
            modules.add(logData.module);
        }
        
        // 添加到缓存
        LogCache.addLog(logData);
        
        // 更新模块过滤器
        updateModuleFilter();
        
        // 重新渲染日志
        renderLogs();
        
        // 更新计数
        updateLogCount();
        
        // 自动滚动
        if (autoScroll && logContainer) {
            logContainer.scrollTop = logContainer.scrollHeight;
        }
    }

    function updateModuleFilter() {
        if (!moduleFilter) return;
        
        const currentValue = moduleFilter.value;
        
        moduleFilter.innerHTML = '<option value="all">所有模块</option>';
        
        Array.from(modules).sort().forEach(module => {
            const option = document.createElement('option');
            option.value = module;
            option.textContent = module;
            moduleFilter.appendChild(option);
        });
        
        if (currentValue && Array.from(moduleFilter.options).some(opt => opt.value === currentValue)) {
            moduleFilter.value = currentValue;
        }
    }

    function updateLogCount() {
        if (logCount) {
            logCount.textContent = logs.length;
        }
    }

    function applyFilters() {
        renderLogs();
    }

    function renderLogs() {
        if (!logContainer) return;
        
        let filteredLogs = logs;
        
        // 设备过滤
        if (selectedDevice) {
            filteredLogs = filteredLogs.filter(log => log.deviceId === selectedDevice);
        }
        
        // 级别过滤 - 复选框形式
        if (levelFilter) {
            const levelCheckboxes = levelFilter.querySelectorAll('input[type="checkbox"]');
            const selectedLevels = Array.from(levelCheckboxes)
                .filter(checkbox => checkbox.checked)
                .map(checkbox => checkbox.value);
            
            // 如果没有选择"所有级别"且有选择其他级别
            if (!selectedLevels.includes('all') && selectedLevels.length > 0) {
                filteredLogs = filteredLogs.filter(log => selectedLevels.includes(log.level));
            }
        }
        
        // 模块过滤 - 单选模式
        if (moduleFilter && moduleFilter.value !== 'all') {
            filteredLogs = filteredLogs.filter(log => log.module === moduleFilter.value);
        }
        
        // 会话过滤
        if (sessionFilter && sessionFilter.value !== 'all') {
            if (sessionFilter.value === 'current') {
                // 获取当前活跃会话
                const sessions = deviceSessions.get(selectedDevice) || [];
                const activeSession = sessions.find(s => s.is_active);
                if (activeSession) {
                    filteredLogs = filteredLogs.filter(log => log.sessionId === activeSession.id);
                }
            } else {
                filteredLogs = filteredLogs.filter(log => log.sessionId === sessionFilter.value);
            }
        }
        
        // 搜索过滤
        if (searchInput && searchInput.value.trim()) {
            const searchTerm = searchInput.value.trim().toLowerCase();
            filteredLogs = filteredLogs.filter(log => 
                log.message.toLowerCase().includes(searchTerm) ||
                (log.module && log.module.toLowerCase().includes(searchTerm))
            );
        }
        
        // 去重处理
        if (useDeduplication) {
            const seen = new Set();
            filteredLogs = filteredLogs.filter(log => {
                const key = `${log.level}-${log.module}-${log.message}`;
                if (seen.has(key)) {
                    return false;
                }
                seen.add(key);
                return true;
            });
        }
        
        // 渲染日志
        logContainer.innerHTML = '';
        
        filteredLogs.forEach(log => {
            const logElement = createLogElement(log);
            logContainer.appendChild(logElement);
        });
        
        // 自动滚动到底部
        if (autoScroll) {
            logContainer.scrollTop = logContainer.scrollHeight;
        }
    }

    function createLogElement(log) {
        const logElement = document.createElement('div');
        logElement.className = `log-entry log-${log.level}`;
        logElement.dataset.logId = log.id || Date.now() + Math.random().toString(36).substr(2, 9);
        logElement.dataset.timestamp = log.timestamp;
        logElement.dataset.level = log.level;
        logElement.dataset.module = log.module || 'UNKNOWN';
        logElement.dataset.message = log.message || '';
        
        const timestamp = formatTimestamp(log.timestamp);
        const level = log.level.toUpperCase();
        const module = log.module || 'UNKNOWN';
        const message = log.message || '';
        
        logElement.innerHTML = `
            <span class="log-timestamp">${timestamp}</span>
            <span class="log-level log-level-${log.level}">${level}</span>
            <span class="log-module">${module}</span>
            <span class="log-message">${message}</span>
        `;
        
        // 添加右键菜单事件
        logElement.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            showContextMenu(e, logElement, 'log');
        });
        
        return logElement;
    }    
    // 右键菜单功能
    function showContextMenu(event, element, type = 'log') {
        const contextMenu = document.getElementById('context-menu');
        if (!contextMenu) return;
        
        // 先移除之前可能存在的事件监听器
        document.removeEventListener('click', window.closeContextMenuHandler);
        
        // 设置菜单位置
        contextMenu.style.left = `${event.pageX}px`;
        contextMenu.style.top = `${event.pageY}px`;
        
        // 显示菜单
        contextMenu.classList.add('active');
        
        // 存储当前元素信息
        if (type === 'log') {
            contextMenu.dataset.currentLogId = element.dataset.logId;
            contextMenu.dataset.type = 'log';
        } else if (type === 'device') {
            contextMenu.dataset.deviceId = element;
            contextMenu.dataset.type = 'device';
        }
        
        // 阻止事件冒泡，防止立即触发关闭
        event.stopPropagation();
        
        // 点击其他区域关闭菜单
        window.closeContextMenuHandler = (e) => {
            // 如果点击的不是菜单本身
            if (!contextMenu.contains(e.target)) {
                contextMenu.classList.remove('active');
                document.removeEventListener('click', window.closeContextMenuHandler);
            }
        };
        
        // 延迟添加事件监听器，防止立即触发
        setTimeout(() => {
            document.addEventListener('click', window.closeContextMenuHandler);
        }, 10);
    }
    
    // 初始化右键菜单
    function initContextMenu() {
        const contextMenu = document.getElementById('context-menu');
        if (!contextMenu) return;
        
        // 处理菜单项点击
        contextMenu.addEventListener('click', (e) => {
            const action = e.target.closest('.context-menu-item')?.dataset.action;
            if (!action) return;
            
            const type = contextMenu.dataset.type;
            
            if (type === 'log') {
                const logId = contextMenu.dataset.currentLogId;
                const logElement = document.querySelector(`.log-entry[data-log-id="${logId}"]`);
                
                if (!logElement) return;
                
                switch (action) {
                    case 'copy':
                        // 复制日志内容
                        const logText = `${logElement.dataset.timestamp} [${logElement.dataset.level}] [${logElement.dataset.module}] ${logElement.dataset.message}`;
                        navigator.clipboard.writeText(logText)
                            .then(() => showToast('日志内容已复制到剪贴板'))
                            .catch(err => showToast('复制失败: ' + err, 'error'));
                        break;
                        
                    case 'delete':
                        // 删除日志
                        deleteLog(logId, logElement);
                        break;
                }
            } else if (type === 'device') {
                const deviceId = contextMenu.dataset.deviceId;
                
                if (!deviceId) return;
                
                switch (action) {
                    case 'copy':
                        // 复制设备ID
                        navigator.clipboard.writeText(deviceId)
                            .then(() => showToast('设备ID已复制到剪贴板'))
                            .catch(err => showToast('复制失败: ' + err, 'error'));
                        break;
                        
                    case 'delete':
                        // 删除设备
                        deleteDevice(deviceId);
                        break;
                }
            }
        });
    }
    
    // 删除日志
    function deleteLog(logId, logElement) {
        if (!logElement) return;
        
        // 从DOM中移除
        logElement.remove();
        
        // 从日志数组中移除
        const index = logs.findIndex(log => log.id === logId || 
            (log.timestamp === logElement.dataset.timestamp && 
             log.level === logElement.dataset.level && 
             log.module === logElement.dataset.module && 
             log.message === logElement.dataset.message));
        
        if (index !== -1) {
            logs.splice(index, 1);
            
            // 更新计数
            updateLogCount();
            
            // 显示成功消息
            showToast('日志已删除');
        }
    }
    
    // UI 控制函数
    function initFiltersToggle() {
        const filtersToggle = document.getElementById('filters-toggle');
        const filterSecondary = document.getElementById('filter-secondary');
        
        if (!filtersToggle || !filterSecondary) return;
        
        filtersToggle.addEventListener('click', () => {
            const expanded = filterSecondary.classList.contains('expanded');
            
            if (expanded) {
                filterSecondary.classList.remove('expanded');
                filtersToggle.classList.remove('expanded');
                filtersToggle.title = '展开更多过滤器';
                UserSettings.set('filtersExpanded', false);
            } else {
                filterSecondary.classList.add('expanded');
                filtersToggle.classList.add('expanded');
                filtersToggle.title = '收起过滤器';
                UserSettings.set('filtersExpanded', true);
            }
        });
        
        if (window.innerWidth >= 768) {
            filterSecondary.classList.add('expanded');
            filtersToggle.classList.add('expanded');
            filtersToggle.title = '收起过滤器';
        }
        
        window.addEventListener('resize', () => {
            if (window.innerWidth >= 768 && !filterSecondary.classList.contains('expanded')) {
                filterSecondary.classList.add('expanded');
                filtersToggle.classList.add('expanded');
                filtersToggle.title = '收起过滤器';
                UserSettings.set('filtersExpanded', true);
            }
        });
    }

    function initSidebarToggle() {
        if (!sidebarToggle || !sidebar) return;
        
        const sidebarOverlay = document.getElementById('sidebar-overlay');
        const content = document.querySelector('.content');
        
        sidebarToggle.addEventListener('click', () => {
            const isExpanded = sidebar.classList.contains('expanded');
            
            if (window.innerWidth <= 1024) {
                if (isExpanded) {
                    sidebar.classList.remove('expanded');
                    if (sidebarOverlay) {
                        sidebarOverlay.classList.remove('active');
                    }
                } else {
                    sidebar.classList.add('expanded');
                    if (sidebarOverlay) {
                        sidebarOverlay.classList.add('active');
                    }
                }
            } else {
                const willCollapse = !sidebar.classList.contains('collapsed');
                sidebar.classList.toggle('collapsed');
                if (content) {
                    content.classList.toggle('sidebar-collapsed', willCollapse);
                }
                UserSettings.set('sidebarCollapsed', willCollapse);
            }
        });
        
        if (sidebarOverlay) {
            sidebarOverlay.addEventListener('click', () => {
                sidebar.classList.remove('expanded');
                sidebarOverlay.classList.remove('active');
            });
        }
        
        window.addEventListener('resize', () => {
            if (window.innerWidth > 1024) {
                sidebar.classList.remove('expanded');
                if (sidebarOverlay) {
                    sidebarOverlay.classList.remove('active');
                }
            } else {
                sidebar.classList.remove('collapsed');
            }
        });
    }

    function showToast(message, timeout = 1800) {
        if (!toast) return;
        toast.textContent = message;
        toast.classList.add('show');
        clearTimeout(toast._hideTimer);
        toast._hideTimer = setTimeout(() => {
            toast.classList.remove('show');
        }, timeout);
    }

    function initCopySessionId() {
        if (!copySessionBtn) return;
        copySessionBtn.addEventListener('click', async () => {
            const sessionIdEl = document.getElementById('current-session-id');
            if (!sessionIdEl) return;
            const text = sessionIdEl.textContent || '';
            try {
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    await navigator.clipboard.writeText(text);
                } else {
                    const ta = document.createElement('textarea');
                    ta.value = text;
                    document.body.appendChild(ta);
                    ta.select();
                    document.execCommand('copy');
                    ta.remove();
                }
                showToast('会话ID 已复制');
            } catch (err) {
                console.error('复制失败', err);
                showToast('复制失败');
            }
        });
    }

    function initCollapseAllSessions() {
        if (!collapseAllSessionsBtn) return;
        
        collapseAllSessionsBtn.addEventListener('click', () => {
            // 折叠所有会话
            sessionCollapseStates.clear();
            const sessionElements = document.querySelectorAll('.session-group');
            sessionElements.forEach(element => {
                element.classList.add('collapsed');
                const sessionId = element.getAttribute('data-session-id');
                if (sessionId) {
                    sessionCollapseStates.set(sessionId, true);
                }
            });
            
            // 保存状态
            SessionCache.save();
            showToast('已折叠所有会话');
        });
    }

    function initBackToRealtime() {
        if (!backToRealtimeBtn) return;
        
        backToRealtimeBtn.addEventListener('click', () => {
            // 清除所有过滤器，回到实时模式
            if (levelFilter) levelFilter.value = 'all';
            if (moduleFilter) moduleFilter.value = 'all';
            if (sessionFilter) sessionFilter.value = 'all';
            if (searchInput) searchInput.value = '';
            
            // 启用自动滚动
            autoScroll = true;
            if (toggleAutoScrollBtn) {
                toggleAutoScrollBtn.classList.add('active');
                toggleAutoScrollBtn.title = '关闭自动滚动';
            }
            
            // 更新状态指示器为实时模式
            updateStatusIndicator('realtime');
            
            // 保存设置
            UserSettings.save({
                levelFilter: 'all',
                moduleFilter: 'all',
                sessionFilter: 'all',
                searchText: '',
                autoScroll: true
            });
            
            // 重新渲染
            applyFilters();
            
            // 滚动到底部
            if (logContainer) {
                logContainer.scrollTop = logContainer.scrollHeight;
            }
            
            // 隐藏按钮
            backToRealtimeBtn.style.display = 'none';
            
            showToast('已返回实时模式');
        });
    }

    // 更新状态指示器
    function updateStatusIndicator(mode, deviceName = '', sessionId = '') {
        const logStatus = document.querySelector('.log-status');
        if (!logStatus) return;
        
        const statusIcon = logStatus.querySelector('.material-icons');
        const statusText = logStatus.querySelector('span:last-child');
        
        if (!statusIcon || !statusText) return;
        
        // 移除所有状态类
        logStatus.classList.remove('realtime', 'history');
        
        switch (mode) {
            case 'realtime':
                logStatus.classList.add('realtime');
                statusIcon.textContent = 'circle';
                if (selectedDevice && devices.has(selectedDevice)) {
                    const device = devices.get(selectedDevice);
                    statusText.textContent = `实时日志 - ${device.name || selectedDevice}`;
                } else {
                    statusText.textContent = '实时日志';
                }
                break;
            case 'history':
                logStatus.classList.add('history');
                statusIcon.textContent = 'history';
                if (sessionId) {
                    statusText.textContent = `历史会话 - ${sessionId.substring(0, 8)}`;
                } else {
                    statusText.textContent = '历史日志';
                }
                break;
            default:
                statusIcon.textContent = 'circle';
                statusText.textContent = '实时日志';
        }
    }

    // 监听过滤器变化，显示/隐藏返回实时按钮
    function checkRealtimeMode() {
        if (!backToRealtimeBtn) return;
        
        const isFiltered = (levelFilter && levelFilter.value !== 'all') ||
                          (moduleFilter && moduleFilter.value !== 'all') ||
                          (sessionFilter && sessionFilter.value !== 'all') ||
                          (searchInput && searchInput.value.trim() !== '') ||
                          !autoScroll;
        
        if (isFiltered) {
            backToRealtimeBtn.style.display = 'inline-flex';
        } else {
            backToRealtimeBtn.style.display = 'none';
        }
    }

    // 错误处理和恢复
    function handleError(error, context) {
        console.error(`错误 [${context}]:`, error);
        
        // 显示错误提示
        showToast(`操作失败: ${context}`, 3000);
        
        // 尝试从缓存恢复
        if (context.includes('加载') || context.includes('连接')) {
            console.log('尝试从缓存恢复数据...');
            restoreFromCache();
        }
    }

    // 网络状态监听
    function initNetworkMonitoring() {
        window.addEventListener('online', () => {
            console.log('网络已连接');
            showToast('网络已恢复');
            
            // 重新连接WebSocket
            if (!socket || socket.readyState !== WebSocket.OPEN) {
                initWebSocket();
            }
            
            // 重新加载数据
            loadDevices();
            loadActiveDevices();
        });
        
        window.addEventListener('offline', () => {
            console.log('网络已断开');
            showToast('网络连接已断开，将使用缓存数据', 3000);
        });
    }

    // 性能优化：虚拟滚动（当日志数量很大时）
    function shouldUseVirtualScrolling() {
        return logs.length > 1000;
    }

    // 主初始化函数
    function initialize() {
        console.log('开始初始化日志监控终端...');
        
        try {
            // 1. 从缓存恢复状态
            restoreFromCache();
            
            // 2. 初始化事件监听器
            initFilterEvents();
            initFiltersToggle();
            initSidebarToggle();
            initCopySessionId();
            initCollapseAllSessions();
            initBackToRealtime();
            initContextMenu();
            
            // 加载用户设置
            loadUserSettings();
            
            // 3. 初始化网络监听
            initNetworkMonitoring();
            
            // 4. 启动自动保存
            startAutoSave();
            
            // 5. 初始化WebSocket连接
            initWebSocket();
            
            // 6. 加载初始数据（如果缓存为空）
            if (devices.size === 0) {
                loadDevices();
                loadActiveDevices();
            }
            
            // 7. 监听过滤器变化
            const filterElements = [levelFilter, moduleFilter, sessionFilter, searchInput];
            filterElements.forEach(element => {
                if (element) {
                    element.addEventListener('change', checkRealtimeMode);
                    element.addEventListener('input', checkRealtimeMode);
                }
            });
            
            if (toggleAutoScrollBtn) {
                toggleAutoScrollBtn.addEventListener('click', () => {
                    setTimeout(checkRealtimeMode, 100);
                });
            }
            
            // 8. 初始检查实时模式
            checkRealtimeMode();
            
            // 9. 初始化状态指示器
            updateStatusIndicator('realtime');
            
            console.log('日志监控终端初始化完成');
            
        } catch (error) {
            handleError(error, '初始化');
        }
    }

    // 启动应用
    initialize();
    
    // 导出一些函数供调试使用
    window.LogMonitor = {
        CacheManager,
        UserSettings,
        LogCache,
        DeviceCache,
        SessionCache,
        restoreFromCache,
        saveCurrentSettings,
        clearAllCache: () => {
            CacheManager.clear();
            location.reload();
        },
        getStats: () => ({
            logs: logs.length,
            devices: devices.size,
            activeDevices: activeDevices.size,
            modules: modules.size,
            cacheSize: CacheManager.getSize()
        })
    };
});